package com.ma.schoolproject.service.Imp;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ma.schoolproject.entitys.Book;
import com.ma.schoolproject.entitys.File;
import com.ma.schoolproject.entitys.User;
import com.ma.schoolproject.mapper.BookMapper;
import com.ma.schoolproject.mapper.UserMapper;
import com.ma.schoolproject.service.BookService;
import com.ma.schoolproject.utils.FilesUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Map;

@Service
@Transactional
@RequiredArgsConstructor
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    private final BookMapper bookMapper;
    private final FilesUtils filesUtils;
    private final UserMapper userMapper;
    private final FileConfigProperties fileConfigProperties;
    private final FileMapper fileMapper;

    /**
     * 保存书籍信息
     * @param files
     * @param book
     * @return
     */
    @Override
    public SaResult savaBook(MultipartFile[] files, Book book) {
        ArrayList<String> filePath=new ArrayList<>();
        for (MultipartFile file : files) {
            Map<String, Object> upload = filesUtils.upload(file);
            if(upload.get("filePath")==null) return SaResult.error("请传递图片格式为.jpg....");
            filePath.add(upload.get("filePath").toString());
        }
        book.setCoverImage(filePath.get(0));
        book.setBackImage(filePath.get(1));
        //提交用户
        String loginId = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,loginId);
        User user = userMapper.selectOne(wrapper);
        book.setSubmitUser(user.getId());
        return bookMapper.insert(book)>0?SaResult.ok("保存成功"):SaResult.error("保存失败");
    }

    /**
     * 查询书籍内容
     * @param id
     * @return
     */
    @Override
    public SaResult getBookById(Long id) {
        Book book = bookMapper.selectById(id);
        if (book==null)return SaResult.error("未查询出书籍信息");
        book.setCoverImage(book.getCoverImage().replace(fileConfigProperties.getImgAddress(),fileConfigProperties.getImgHttpAddress()));
        book.setBackImage(book.getBackImage().replace(fileConfigProperties.getImgAddress(),fileConfigProperties.getImgHttpAddress()));
        //todo书籍内容填充
        LambdaQueryWrapper<File> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(File::getBookId,book.getId());
        File file = fileMapper.selectOne(wrapper);
        book.setFileName(file);
        return SaResult.data(book);
    }

    /**
     * 保存书籍内容
     * @param file
     * @param bookId
     * @return
     */
    @Override
    public SaResult savaBookContent(MultipartFile file, Long bookId) {
        Map<String, Object> upload = filesUtils.upload(file);
        if(upload.get("filePath")==null) return SaResult.error("请传递文件格式为.pdf....");
        File file1 = File.builder().bookId(bookId).pathFileName(upload.get("filePath").toString()).build();
        return fileMapper.insert(file1)>0?SaResult.ok("保存成功"):SaResult.error("保存失败");
    }

//    /**
//     * 修改图片
//     * @param files
//     * @param book
//     * @return
//     */
//    @Override
//    public SaResult updateBook(MultipartFile[] files, Book book) {
//        Book book1 = bookMapper.selectById(book.getId());
//        if (book1==null) return SaResult.error("未查询出书籍信息");
//        if (files!=null&&files[0]!=null){
//            Map<String, Object> upload = filesUtils.upload(files[0]);
//            book.setCoverImage(upload.get("filePath").toString());
//        }
//        if(files!=null&&files[1]!=null){
//            Map<String, Object> upload = filesUtils.upload(files[1]);
//            book.setCoverImage(upload.get("filePath").toString());
//        }
//        return bookMapper.updateById(book)>0?SaResult.ok("修改成功"):SaResult.error("修改失败");
//    }

    /**
     * 修改书籍内容
     * @param file
     * @return
     */
    @Override
    public SaResult updateBookContent(MultipartFile file,Long bookId) {
        LambdaQueryWrapper<File> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(File::getBookId,bookId);
        File file1 = fileMapper.selectOne(wrapper);
        if (file1==null)return SaResult.error("未查询出书籍内容信息");
        Map<String, Object> upload = filesUtils.upload(file);
        if(upload.get("filePath")==null) return SaResult.error("请传递文件格式为.pdf....");
        File filePath = File.builder().bookId(bookId).pathFileName(upload.get("filePath").toString()).build();
        UpdateWrapper<File> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq(" book_id",bookId).set("path_file_name",filePath);
        return fileMapper.update(file1,updateWrapper)>0?SaResult.ok("修改成功"):SaResult.error("修改失败");
    }

//    /**
//     * 删除书籍
//     * @param id
//     * @return
//     */
//    @Override
//    public SaResult deleteBook(Long id) {
//        Book book = bookMapper.selectById(id);
//        if (book==null) return SaResult.error("未查询出书籍信息");
//        //删除书籍信息
//        bookMapper.deleteById(id);
//        filesUtils.deleteFile(book.getBackImage());//删除图片
//        filesUtils.deleteFile(book.getCoverImage());//删除图片
//        //删除书籍内容信息
//        LambdaQueryWrapper<File> wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(File::getBookId,book.getId());
//        File file = fileMapper.selectOne(wrapper);
//        if (file!=null){
//            fileMapper.deleteById(file.getId());
//            filesUtils.deleteFile(file.getPathFileName());//删除图片
//        }
//        return SaResult.ok("删除成功");
//    }

    /**
     * 根据书籍id查询书籍内容
     * @param id
     * @return
     */
    @Override
    public SaResult fileByBookId(Long id) {
        LambdaQueryWrapper<File> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(File::getBookId,id);
        File file = fileMapper.selectOne(wrapper);
        return SaResult.data(file);
    }

    @Cacheable(value = "bookCache",key = "#id")  //查看
    public SaResult selectBook(Long id) {
        Book book = bookMapper.selectById(id);
        if (book==null) return SaResult.error("未查询出书籍信息");
        book.setCoverImage(book.getCoverImage().replace(fileProperties.getImgAddress(), fileProperties.getImgHttpAddress()));
        book.setBackImage(book.getBackImage().replace(fileProperties.getImgAddress(), fileProperties.getImgHttpAddress()));
        LambdaQueryWrapper<File> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(File::getBookId, id);
        File file = fileMapper.selectOne(queryWrapper);
        if (file!=null) book.setFileName(file.getPathFileName().replace(fileProperties.getPdfAddress(),fileProperties.getPdfHttpAddress()));
        return SaResult.data(book);
    }

    @Override
    @CachePut(value = "bookCache",key = "#book.id")     //修改
    public SaResult updateBook(MultipartFile[] files, Book book) {
        Book book1 = bookMapper.selectById(book.getId());
        if(book1==null) return  SaResult.error("未查询出要修改的书籍信息");
        if (files!=null&&files[0]!=null){
            Map<String, Object> upload = filesUtils.upload(files[0]);
            if (upload.get("filePath") == null) return SaResult.error("未按照规定格式传递文件");
            book.setCoverImage(upload.get("filePath").toString());
        }
        if (files!=null&&files[1]!=null){
            Map<String, Object> upload = filesUtils.upload(files[0]);
            if (upload.get("filePath") == null) return SaResult.error("未按照规定格式传递文件");
            book.setBackImage(upload.get("filePath").toString());
        }
        int result = bookMapper.updateById(book);
        if(result > 0) {
            Book updated = bookMapper.selectById(book.getId());
            return SaResult.data(updated);
        }
        return SaResult.error("修改失败");
    }

    @Override
    @CacheEvict(value = "bookCache",key = "#id")   //删除
    public SaResult deleteBook(Long id) {
        Book book = bookMapper.selectById(id);
        if(book==null) return SaResult.error("未找到需要删除的书籍信息");
        String coverImage = book.getCoverImage();
        String backImage = book.getBackImage();
        filesUtils.deleteFile(coverImage);
        filesUtils.deleteFile(backImage);
        //查询是否有上传书籍内容信息
        LambdaQueryWrapper<File> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(File::getBookId,book.getId());
        File file = fileMapper.selectOne(queryWrapper);
        if(file!=null){
            filesUtils.deleteFile(file.getPathFileName());
            fileMapper.delete(queryWrapper);
        }
        bookMapper.deleteById(id);
        return SaResult.ok("删除成功");
    }
}
